//
//  HotViewController.m
//  Journey
//
//  Created by dllo on 16/5/20.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "HotViewController.h"
#import "SSNetworking.h"
#import "HotImageTableViewCell.h"
#import "HotTextTableViewCell.h"
#import "HotModel.h"
#import "HotDetailViewController.h"
#import "YNDataReading.h"

static NSString *const HotViewCell = @"HotViewCELL";
static NSString *const HotImageCell = @"HotImageCELL";
@interface HotViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>
@property(nonatomic,strong)UITableView *HottableView;
@property(nonatomic,strong)NSMutableArray *hotArray;
//刷新
@property(nonatomic,assign)NSInteger nextPage;
@property(nonatomic,assign)BOOL isUpLoading;
@property(nonatomic,strong)NSMutableArray *imageArray;


//搜索
@property(nonatomic,strong)NSMutableArray *searchArray;

@end

@implementation HotViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  //  self.view.backgroundColor = [UIColor whiteColor];
    self.hotArray = [NSMutableArray array];
    self.searchArray = [NSMutableArray array];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.placeholder = @"搜索用户,目的地,帖子,折扣";
    
    self.HottableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.HottableView];
    self.HottableView.delegate = self;
    self.HottableView.dataSource = self;
    self.HottableView.tableHeaderView = self.searchController.searchBar;
    
    self.HottableView.showsVerticalScrollIndicator = NO;
    
    //注册
    [self.HottableView registerClass:[HotImageTableViewCell class] forCellReuseIdentifier:HotImageCell];
    [self.HottableView registerClass:[HotTextTableViewCell class] forCellReuseIdentifier:HotViewCell];
    
    self.definesPresentationContext = YES;
    //加载条
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    
    
    self.imageArray = [NSMutableArray array];
    for (int i = 1; i < 4; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"loading_0%d",i]];
        [self.imageArray addObject:image];
    }

    self.isUpLoading = NO;
    [self addFooter];
    [self addHeader];
    
    //创建数据库表
    [[DataBaseHandle shareDataBaseHandle] hotCreatTable];
    
}

-(void)addHeader
{
    __block HotViewController *hotVC = self;
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        
        hotVC.nextPage = 1;
        hotVC.isUpLoading = NO;
        [hotVC getDataList:hotVC.nextPage];
      }];
    
    //普通闲置状态
    [header setImages:self.imageArray forState:MJRefreshStateIdle];
    //松开就可以进行刷新的状态
    [header setImages:self.imageArray forState:MJRefreshStatePulling];
    //正在刷新中的状态
    [header setImages:self.imageArray forState:MJRefreshStateRefreshing];
    self.HottableView.mj_header = header;
    [self.HottableView.mj_header beginRefreshing];
}

-(void)addFooter
{
    __block HotViewController *hotVC = self;
    
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        
        hotVC.nextPage ++;
        hotVC.isUpLoading = YES;
        [hotVC getDataList:hotVC.nextPage];
    }];
    
    [footer setImages:self.imageArray forState:MJRefreshStateRefreshing];
    self.HottableView.mj_footer = footer;
    
}

-(void)getDataList:(NSInteger)nextPage{
    
    [SSNetworking ssGETWithURL:@"http://open.qyer.com/qyer/community/hotbbs/index?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=38.88283798007659&lon=121.539156053574&oauth_token=4ea07b0d41e13f5cb1448a45a3613e45&page=1&track_app_channel=App%2520Store&track_app_version=6.9.0&track_device_info=iPhone8%2C1&track_deviceid=F417850E-117E-4BF4-AAA6-3AD14E14E3C1&track_os=ios%25209.3.1&track_user_id=7891151&v=1" parameter:nil success:^(id result) {
        
        [[YNDataReading shareYNataReading]writeCachePlist:@"hotData" result:result];
        NSDictionary *dic = [[YNDataReading shareYNataReading] readCachePlist:@"hotData"];
        NSArray *dataArray = [dic objectForKey:@"data"];
        
         if (self.isUpLoading == NO) {
            [self.hotArray removeAllObjects];
        }
        
        
        for (NSDictionary *dic in dataArray) {
            HotModel *model = [[HotModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
          //  NSLog(@"======%@",model.title);
            [self.hotArray addObject:model];
        }
        
        //停止刷新
        [self.HottableView.mj_footer endRefreshing];
        [self.HottableView.mj_header endRefreshing];
        
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        [self.HottableView reloadData];
        
    } failure:^(NSError *error) {
        
        
    } network:^(BOOL networking) {
        
        NSDictionary *dic = [[YNDataReading shareYNataReading] readCachePlist:@"hotData"];
        NSArray *dataArray = [dic objectForKey:@"data"];
        
        if (self.isUpLoading == NO) {
            [self.hotArray removeAllObjects];
        }
        
        
        for (NSDictionary *dic in dataArray) {
            HotModel *model = [[HotModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.hotArray addObject:model];
        }
        
        //停止刷新
        [self.HottableView.mj_footer endRefreshing];
        [self.HottableView.mj_header endRefreshing];
        
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        [self.HottableView reloadData];

        
    }];
    
 }





-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchController.active) {
        return 220;
    }
    
    HotModel *model = [self.hotArray objectAtIndex: indexPath.row];
    NSMutableArray *tempArray = model.bigpic_arr;
    if (tempArray.count == 0) {
        return 150;
    }
    return 220;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return  self.searchArray.count;
    }
    return self.hotArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.searchController.active) {
        HotModel *model = [self.searchArray objectAtIndex: indexPath.row];
        NSMutableArray *tempArray = model.bigpic_arr;
        if (tempArray.count == 0) {
            HotTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HotViewCell];
            cell.hotModel = model;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        }
        
        HotImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HotImageCell];
        cell.hotModel = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }else{

    HotModel *model = [self.hotArray objectAtIndex: indexPath.row];
    
    NSMutableArray *tempArray = model.bigpic_arr;
    if (tempArray.count == 0) {
        HotTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HotViewCell];
        cell.hotModel = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    
    HotImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HotImageCell];
    cell.hotModel = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HotModel *model = nil;
    if (self.searchController.active) {
        
    model = [self.searchArray objectAtIndex:indexPath.row];
    
    }else{
     model = [self.hotArray objectAtIndex:indexPath.row];
}

    HotDetailViewController *hotVC = [[HotDetailViewController alloc] init];
 //   UINavigationController *hotNa = [[UINavigationController alloc] initWithRootViewController:hotVC];
    hotVC.hotModel = model;
    hotVC.HotString = model.appview_url;
    [self.navigationController pushViewController:hotVC animated:YES];
}




-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    
//    NSLog(@"===%@",searchString);
    
    [self.searchArray removeAllObjects];
    for (HotModel *model in self.hotArray) {
        
        //rangeOfString:方法是在movieName中搜索是否包含searchText
        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
        //NSNotFound 表示请求操作的某个内容没有发现
        if ([model.title rangeOfString:searchString].location != NSNotFound) {
            
            [self.searchArray addObject:model];
        }
    }
//    NSLog(@"searchArray===%@",self.searchArray);
    
    [self.HottableView reloadData];
    
}

//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    NSLog(@"111");
    if (self.searchController.active) {
        
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
